package com.agrimall.util;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.models.QwenParam;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;

import java.io.InputStream;
import java.util.Properties;

/**
 * AI工具类
 * 封装通义千问API调用逻辑
 */
public class AIUtil {
    private static String apiKey;
    private static final String DEFAULT_MODEL = "qwen-turbo";
    private static final int DEFAULT_MAX_TOKENS = 1500;
    private static final float DEFAULT_TEMPERATURE = 0.85f;
    private static final double DEFAULT_TOP_P = 0.8d;
    private static final float DEFAULT_REPETITION_PENALTY = 1.0f;
    
    static {
        try {
            // 从配置文件加载API Key
            InputStream is = AIUtil.class.getClassLoader().getResourceAsStream("db.properties");
            if (is != null) {
                Properties props = new Properties();
                props.load(is);
                apiKey = props.getProperty("ai.api.key");
                is.close();
            }
            if (apiKey == null || apiKey.trim().isEmpty()) {
                throw new RuntimeException("AI API Key未配置，请在db.properties中配置ai.api.key");
            }
        } catch (Exception e) {
            throw new RuntimeException("加载AI配置失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 调用AI回答问题
     * @param question 用户问题
     * @return AI回答内容
     * @throws NoApiKeyException API Key异常
     * @throws ApiException API调用异常
     * @throws InputRequiredException 输入参数异常
     */
    public static String askQuestion(String question) throws NoApiKeyException, ApiException, InputRequiredException {
        if (question == null || question.trim().isEmpty()) {
            return "请输入您的问题";
        }
        
        // 构建农业相关的提示词
        String prompt = "你是一个专业的农业咨询助手，专门帮助用户解答农产品相关问题。请用简洁、专业、易懂的方式回答以下问题：\n\n" + question;
        
        Generation gen = new Generation();
        QwenParam params = QwenParam.builder()
                .model(DEFAULT_MODEL)
                .prompt(prompt)
                .seed(1234)
                .topP(DEFAULT_TOP_P)
                .resultFormat("message")
                .maxTokens(DEFAULT_MAX_TOKENS)
                .temperature(DEFAULT_TEMPERATURE)
                .repetitionPenalty(DEFAULT_REPETITION_PENALTY)
                .apiKey(apiKey)
                .build();
        
        GenerationResult result = gen.call(params);
        return result.getOutput().getChoices().get(0).getMessage().getContent();
    }
    
    /**
     * 获取API Key（用于测试）
     */
    public static String getApiKey() {
        return apiKey != null && !apiKey.isEmpty() ? "已配置" : "未配置";
    }
}


